package com.ruoyi.websocket;

import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * description:
 * auth fcb
 * date 2025-04-02 17:18
 **/
@Component
@ServerEndpoint("/websocket/{userIdBusinessType}")
public class WebSocketServer {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WebSocketServer.class);

    private Session session;

    private String sessionKey;

    /**
     *
     * @param session
     * @param userIdBusinessType 用户id-业务类型
     */
    @OnOpen
    public void onOpen(Session session,  @PathParam("userIdBusinessType") String userIdBusinessType) {
        log.info("websocket连接建立，用户连接和业务类型：{}", userIdBusinessType);
        this.session = session;
        this.sessionKey = userIdBusinessType;
        WebSocketManager.addSession(sessionKey, session);
    }

    @OnClose
    public void onClose() {
        WebSocketManager.removeSession(sessionKey);
        WebSocketManager.removeLargeScreenArea(sessionKey);
        log.info("WebSocket连接关闭,sessionKey：{}", sessionKey);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        //SpringUtils.getBean("")
        log.info("来自SessionId:{}的消息:{}", sessionKey, message);
        Object o = SpringUtils.getBean(WebSocketBusinessService.class).executeBusinessAngGetResult(sessionKey, message);
        // todo 根据消息类型决定如何处理返回值
        if (message.contains("@")) {
            String[] split = message.split("@");
            if (StringUtils.equals(split[0], "largeScreen")) {
                //来自数据大屏
                WebSocketManager.setLargeScreenArea(sessionKey, split[1]);
            }
        }
        //session.getAsyncRemote().sendText("hello");
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("SessionKey:{} 的WebSocket发生错误：{}", sessionKey, ExceptionUtil.getExceptionMessage(error));
    }

    public Session getSession() {
        return session;
    }

    public String getSessionKey() {
        return sessionKey;
    }
}
